<template>
  <div class="stats-container">
    <div class="stats-form stats-customer-form" v-if="type !== 'client-map'">
      <!-- 流程类型 -->
      <el-select
        v-if="type === 'client-satisfaction'"
        v-model="processType"
        :placeholder="$t('report.customer.pla1')"
        @input="processTypeChange"
      >
        <el-option
          v-for="item in processTypeOptions"
          :key="item.code"
          :label="item.desc"
          :value="item.code"
        ></el-option>
      </el-select>

      <biz-team-select 
        v-if="divideByTag" class="stats-team-select biz-team-select" 
        :value="tag" multiple collapse is-auto-select-child @input="chooseTeam" :fetch-func="fetchTeam"/>

      <div class="stats-form-group">
        <date-picker @datePicker="datePicker" />
      </div>
    </div>

    <!-- 客户满意度统计 -->
    <div class="stats-customer-head" v-if="type === 'client-satisfaction'">
      <div class="stats-customer-card">
        <div class="stats-customer-card-info">
          <h3>{{countData.allCustomerCount | convertZero}}</h3>
          <p>{{$t('report.customer.title1')}}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('report.customer.title2')}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </p>
        </div>
        <img :src="customerImage1"/>
      </div>
      <div class="stats-customer-card">
        <div class="stats-customer-card-info">
          <h3>{{countData.newCustomerCount | convertZero}}</h3>
          <p>{{$t('report.customer.title3')}}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('report.customer.title4')}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </p>
        </div>
        <img :src="customerImage2"/>
      </div>
      <div class="stats-customer-card">
        <div class="stats-customer-card-info">
          <h3>{{countData.finishedCustomerCount | convertZero}}</h3>
          <p>{{$t('report.customer.title5')}}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('report.customer.title6')}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </p>
        </div>
        <img :src="customerImage3"/>
      </div>
      <div class="stats-customer-card">
        <div class="stats-customer-card-info">
          <h3>{{countData.visitRate	| toPercent}}</h3>
          <p>{{$t('report.customer.title7')}}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('report.customer.title8')}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </p>
        </div>
        <img :src="customerImage4"/>
      </div>
    </div>

    <customer-degree-chart 
      :degree-data="degreeData" 
      :team-id="teamId" 
      :time-start="timeStart" 
      :time-end="timeEnd" 
      :evaluate-config="evaluateConfig" 
      :process-type-name="processTypeName"
      :process-type="processType"
      :chart-type="type"
      v-if="type === 'client-satisfaction'"
    ></customer-degree-chart>

    <!-- 客户信息统计 -->
    <div class="stats-row" v-if="type === 'client-statistics'">
      <div class="stats-panel">
        <div class="stats-panel-head">
          <h3>{{$t('report.customer.title9')}}
            <el-popover trigger="hover">
              <ul>
                <li>{{$t('report.customer.title10')}}</li>
                <li>{{$t('report.customer.title11')}}</li>
                <li>{{$t('report.customer.title12')}}</li>
                <li>{{$t('report.customer.title13')}}</li>
                <li>{{$t('report.customer.title14')}}</li>
              </ul>
              <stats-popover-icon slot="reference"></stats-popover-icon>
            </el-popover>
          </h3>
        </div>
        <div class="stats-panel-body">
          <div style="text-align: center;"> 
            <div class="category-btn-group">
              <button
                v-for="btn in btnOptions"
                :key="btn.value"
                type="button"
                :class="{'stats-checked': category == btn.value}"
                @click="chooseCategory(btn.value)">
                {{ btn.name }}
              </button>
            </div>
          </div>
          
          <div class="category-chart-wrap">

            <!-- start 客户工单统计图表 -->
            <div id="chart" :style="{height: (allowExpand && expand) ? '720px' : '480px'}"></div>
            <!-- end 客户工单统计图表 -->

            <!-- start 加载更多 -->
            <div class="load-more">
              <el-button v-show="!currentTabPageData.isAllEnd && isShowLomeText" @click="categoryJump" type="text">{{$t('common.base.tip.loadMore')}}</el-button>
              <span v-show="currentTabPageData.isAllEnd && isShowLomeText" class="color9a9a9a" type="text" disabled>{{$t('common.base.tip.loadedAllRes2')}}</span>
            </div>
            <!-- end 加载更多 -->

            <div class="stats-table-expand no-border" :class="{'stats-table-isExpand': expand}" v-if="allowExpand">
              <button type="button" @click="expand = !expand;expand && trackEventHandler('more')">
                <i class="iconfont icon-zhankaisanjiao"></i> {{expand ? $t('report.staffEventTable.label1') : $t('report.staffEventTable.label4')}}
              </button>
            </div>
            <stats-chart-empty v-if="categoryEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
            <div class="stats-table-wrap" v-if="showTable">
              <div class="stats-table-header">
                <h3>{{category === $t('common.base.event') ?  $t('report.stationTable.title2') : $t('common.label.taskList')}}</h3>

                <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">
                  {{ $t('common.base.export') }}
                </button>
                <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button>
                <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
              </div>
              <client-statistics-table :page="page" :category="category" @jump="jump"></client-statistics-table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 客户地图 -->
    <customer-map v-if="type === 'client-map'" :chart-type="type"></customer-map>
  </div>
</template>

<script>
import { t } from '@src/locales';
import { isOpenData } from '@src/util/platform';
/* global AMap, moment, _init_data*/
import _ from 'lodash';
import http from 'src/util/HttpUtil';
import qs from 'src/util/querystring';
import { checkButtonDisplayed } from '@src/util/dom';

import echarts from 'packages/Echarts';
import Loading from 'packages/BaseLoading';
import SampleTooltip from 'packages/SampleTooltip'

import CustomerMap from './CustomerMap.vue';
import CustomerDegreeChart from './CustomerDegreeChart.vue';
import ClientStatisticsTable from './components/ClientStatisticsTable.vue'

import * as ReportApi from '@src/api/ReportApi.ts';

let chart = null;

import { getOssUrl } from '@src/util/assets'
const customerImage1 = getOssUrl('/customer_count.png')
const customerImage2 = getOssUrl('/customer_add.png')
const customerImage3 = getOssUrl('/customer_ser.png')
const customerImage4 = getOssUrl('/file-fill.png')

export default {
  name: 'customer-view',
  data(){
    return {
      customerImage1,
      customerImage2,
      customerImage3,
      customerImage4,
      isOpenData,
      isButtonDisplayed: checkButtonDisplayed(),
      tag: [],  
      // teams: [],
      teamId: '',
      divideByTag: false,
      
      timeStart: '',
      timeEnd: '',
      category: t('common.base.systemKeyword.task'),
      categoryEmpty: false,

      originCategoryData: {},
      degreeData: {},
      countData: {
        allCustomerCount: '--',
        finishedCustomerCount: '--',
        newCustomerCount: '--',
        visitRate	: '--'
      },
      expand: false,

      showTable: false,
      model: {
        pageNum: 1,
        selectType: '',
        customerId: ''
      },
      page: {},

      evaluateConfig: {},
      tabStatus: {
        task: {
          init: true,
          pageNum: 1,
        },
        profit: {
          init: true,
          pageNum: 1,
        },
        sale: {
          init: true,
          pageNum: 1,
        },
        cost: {
          init: true,
          pageNum: 1,
        },
        event: {
          init: true,
          pageNum: 1,
        }
      },
      tabParams: {
        [t('common.base.task')]: 'task',
        [t('report.eventScoreChart.label3')]: 'profit',
        [t('task.list.displayName.profit')]: 'sale',
        [t('task.list.displayName.cost')]: 'cost',
        [t('common.base.event')]: 'event'
      },
      type: '', // 判断入口 client-satisfaction 客户满意度统计/client-statistics 客户信息统计/client-map 客户地图/
      isShowLome: false, // 是否请求完数据
      processType: 'TASK',
      processTypeOptions: [],
      btnOptions: [{
        // category的值为中文value。。国际化需要注意下~
        value: t('common.base.task'),
        name: t('task.list.components.taskNum'),
        trackLabel: 'TASK' // 导出埋点用
      }, {
        value: t('report.eventScoreChart.label3'),
        name: t('report.customer.label2'),
        trackLabel: 'PROFIT'
      }, {
        value: t('task.list.displayName.profit'),
        name: t('report.customer.label3'),
        trackLabel: 'SALE'
      }, {
        value: t('task.list.displayName.cost'),
        name: t('report.customer.label4'),
        trackLabel: 'COST'
      }, {
        value: t('common.base.event'),
        name: t('report.customer.label6'),
        trackLabel: 'EVENT'
      }],
    };
  },
  created() {
    this.type = window.location.href.split('type=')[1];
    if(this.type === 'client-satisfaction') {
      this.fetchStatsCustomerType();
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
    allowExpand(){
      return Object.keys(this.originCategoryData).some(key => this.originCategoryData[key].length > 10);
    },
    categoryData(){
      if(!this.allowExpand) return this.originCategoryData;
      if(this.expand) return this.originCategoryData;

      let origin = this.originCategoryData;
      let { costData, eventData, profitData, saleData, taskData } = origin;

      return {
        costData: this.buildCategoryItemData(costData, 'cost'),
        eventData: this.buildCategoryItemData(eventData, 'event'),
        profitData: this.buildCategoryItemData(profitData, 'profit'),
        saleData: this.buildCategoryItemData(saleData, 'sale'),
        taskData: this.buildCategoryItemData(taskData, 'task'),
      };
    },
    currentTabParam() {
      return this.tabParams[this.category];
    },
    currentTabParamDataStr() {
      return `${this.currentTabParam}Data`;
    },
    currentTabPageData() {
      if(Object.keys(this.categoryData).length <= 0) return {};

      let dataStr = this.currentTabParamDataStr;
      let data = this.categoryData;

      return data[dataStr] || {};
    },
    currentTabPageNum() {
      return this.tabStatus[this.currentTabParam].pageNum;
    },
    // 有数据并请求完成再展示
    isShowLomeText(){
      return this.currentTabPageData.totalCount && this.isShowLome;
    },
    processTypeName() {
      const current = this.processTypeOptions.filter(item => item.code === this.processType);
      return current && current.length ? current[0].desc : '';
    }
  },
  methods: {
    async fetchStatsCustomerType() {
      const { result, success, message } = await ReportApi.queryStatsCustomerType();
      if(success) {
        this.processTypeOptions = result;
      } else {
        console.error(`获取客户满意度筛选维度失败：${message}`)
      }
    },

    buildCategoryItemData(data = {}, categoryStr) {
      return {
        [categoryStr]: data[categoryStr].slice(0, 10),
        totalPage: data.totalPage,
        totalCount: data.totalCount,
      }
    },
    exportAllData(){
      let model = {
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      if(this.category == t('common.base.event')){
        window.location.href = `/api/report/outside/stats/customerTask/event/exportAll?${ qs.stringify(model)}`;
        this.exportTrack(true)
        return
      } 

      let selectType = 'task';
      if(this.category == t('report.eventScoreChart.label3')) selectType = 'profit';
      if(this.category == t('task.list.displayName.profit')) selectType = 'sale';
      if(this.category == t('task.list.displayName.cost')) selectType = 'cost';

      model.selectType = selectType;
      window.location.href = `/api/report/outside/stats/customerTask/exportAll?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportData(){
      let model = {
        selectType: this.model.selectType,
        userId: this.model.customerId,
        tagId: this.teamId
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      let action = '/api/report/outside/stats/customerTask/export';
      if(this.category == t('common.base.event')) action = '/api/report/outside/stats/customerTask/event/export'

      window.location.href = `${action }?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
    exportTrack(isExportAll) {
      const tab = this.btnOptions.find(v => v.value === this.category)?.trackLabel
      
      window.parent.postMessage({
        message: 'exportTrack',
        isExportAll,
        chartType: this.type,
        tab
      }, '*')
    },
    openDetail(id, title, url){    
      let fromId = window.frameElement.getAttribute('id');

      this.$platform.openTab({
        id, 
        title, 
        close: true, 
        url,
        fromId
      });
      
    },
    categoryJump() {
      // 修改为加载更多方式
      this.tabStatus[this.currentTabParam].pageNum++;
      const currentPage = this.tabStatus[this.currentTabParam].pageNum;

      this.isShowLome = false;
      let instance = this.$loading.show(this.$el);
        
      this.fetchCategoryPagingData(currentPage).then(result => {
        let dataStr = this.currentTabParamDataStr;

        // 是否还能加载更多
        const newList = this.originCategoryData[dataStr][this.currentTabParam].concat(result[this.currentTabParam]);
        const isAllEnd = newList.length === this.originCategoryData[dataStr].totalCount;

        this.$set(this.originCategoryData[dataStr], this.currentTabParam, newList);
        this.$set(this.originCategoryData[dataStr], 'isAllEnd', isAllEnd);
        this.setCategoryOption();
      })
        .catch(err => {
          console.log(err)
        })
        .finally(() => {
          this.isShowLome = true;
          instance.hide();
        });

    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        selectType: this.model.selectType,
        userId: this.model.customerId,
        tagId: this.teamId,
        pageSize: 10
      };

      if(this.timeStart) model.timeStart = this.timeStart;
      if(this.timeEnd) model.timeEnd = this.timeEnd;

      return http.post('/api/report/outside/stats/customer/taskList', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
        
      this.fetchTableData().then(result => {
        this.page = result;
        this.showTable = true;
      })
        .catch(err => console.log(err))
        .finally(() => {
          instance.hide();
        })
    },
    // 流程类型切换
    processTypeChange(value) {
      console.log('processTypeChange value', value);
      this.render();
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    chooseTeam(value){
      this.$tdOnEvent('pc：客户报表-选择团队事件');

      // let tag = (Array.isArray(value) ? value[0] : value) || {};
      let tag = value
      this.tag = value;
      this.teamId = tag.map(item => {return item.id}).join(',');

      this.render();

      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TEAM', this.$track)
    },
    // 时间赋值
    initDate(start, end){
      this.timeStart = start;
      this.timeEnd = end;
      this.render();
    },
    // 初始化图表
    initChart(){
      if (this.type === 'client-statistics') {
        this.$nextTick(() => {
          chart = echarts.init(document.getElementById('chart')); 
          chart.on('click', event => {
            let seriesName = event.seriesName;
            let origin = event.data._origin;
            let selectType = 'task';

            if(seriesName == t('report.eventScoreChart.label3')) selectType = 'profit';
            if(seriesName == t('task.list.displayName.profit')) selectType = 'sale';
            if(seriesName == t('task.list.displayName.cost')) selectType = 'cost';
            if(seriesName == t('common.base.event')) selectType = 'event';

            this.model.selectType = selectType;
            this.model.customerId = origin.customerId;
            this.model.pageNum = 1;
            this.renderTable();
          })
        })
      }
    },
    chooseDate(start, end){
      this.$tdOnEvent('pc：客户报表-日期选择事件');

      this.timeStart = start;
      this.timeEnd = end;
      this.render();
    },
    async render(){
      try {
        // this.category = '工单';

        this.isShowLome = false;
        let instance = Loading.show(this.$el);
        let microTask = [];

        microTask.push(this.fetchCustomerCount());
        microTask.push(this.fetchCategoryData());
        microTask.push(this.fetchCustomerDegree());

        let result = await Promise.all(microTask);

        this.reset();
    
        _.assign(this.countData, result[0]);
        
        // 是否还能加载更多参数
        const categoryData = result[1][this.currentTabParam];
        if(categoryData) result[1].isAllEnd = categoryData.length === result[1].totalCount;
        this.$set(this.originCategoryData, `${this.currentTabParam}Data`, result[1]);
        this.$set(this.tabStatus[this.currentTabParam], 'init', false);
        this.degreeData = result[2] || {};

        this.isShowLome = true;
        instance.hide();

        this.showTable = false;
        this.expand = false;
    
        this.setCategoryOption();
      } catch (error) {
        console.log(error)
      }
    },
    /* 选择分类 */
    async chooseCategory(type){
      this.trackEventHandler(type);

      this.category = type;

      let isInit = this.tabStatus[this.currentTabParam].init;

      if (isInit) {
        try {
          this.isShowLome = false;
          let instance = this.$loading.show(this.$el);
          let result = await this.fetchCategoryData() || {};
          let dataStr = this.currentTabParamDataStr;

          result.isAllEnd = result[this.currentTabParam].length === result.totalCount;
          this.tabStatus[this.currentTabParam].init = false;
          this.$set(this.originCategoryData, dataStr, result);

          this.isShowLome = true;
          instance.hide();
        } catch (error) {
          console.log('fetchCategoryData', this.currentTabParam, error)
        }
      } 
      
      this.setCategoryOption();
    },
    setCategoryOption(){
      this.categoryEmpty = false;

      let option = null;

      if(this.category == t('common.base.task')){
        let taskOption = this.getTaskOption();
        if(taskOption) option = this.getCategoryOption(taskOption);
      }

      if(this.category == t('task.list.displayName.profit')){
        let saleOption = this.getSaleOption()
        if(saleOption) option = this.getCategoryOption(saleOption);
      }

      if(this.category == t('report.eventScoreChart.label3')){
        let profitOption = this.getProfitOption();
        if(profitOption) option = this.getCategoryOption(profitOption);
      }

      // cost
      if(this.category == t('task.list.displayName.cost')){
        let costOption = this.getCostOption();
        if(costOption) option = this.getCategoryOption(costOption);
      }

      if(this.category == t('common.base.event')){
        let eventOption = this.getEventOption();
        if(eventOption) option = this.getCategoryOption(eventOption);
      }
      
      this.$nextTick(() => {
        if (this.type === 'client-statistics') {
          chart.clear();
          chart.resize();
        }
        if(null == option){
          this.categoryEmpty = true;
          return
        }
        this.categoryEmpty = false;
        if (this.type === 'client-statistics') {
          chart.setOption(option);
        }
      })
    }, 
    getTaskOption(){
      let data = this.categoryData.taskData.task || [];
      // data = data.filter(item => item.taskCount > 0);

      if(data.length == 0) return null;

      let yAxisData = [];
      let seriesData = [];
      let series = [];

      data.sort((prev, next) => prev.taskCount - next.taskCount).forEach(item => {
        yAxisData.push(item.customerName);

        seriesData.push({
          value: item.taskCount,
          _origin: item
        });
      });

      series.push({
        name: t('common.base.task'),
        type: 'bar',
        barMaxWidth: '20px',
        data: seriesData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        legend: [t('common.base.task')],
        color: ['#6da9e8'],
        yAxisData,
        series
      }
    },  
    getSaleOption(){
      let data = this.categoryData.saleData.sale || [];
      // data = data.filter(item => item.saleSum > 0);

      if(data.length == 0) return null;

      let yAxisData = [];
      let seriesData = [];
      let series = [];

      data.sort((prev, next) => prev.saleSum - next.saleSum).forEach(item => {
        yAxisData.push(item.customerName);

        seriesData.push({
          value: item.saleSum,
          _origin: item
        });
      });

      series.push({
        name: t('task.list.displayName.profit'),
        type: 'bar',
        barMaxWidth: '20px',
        data: seriesData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        legend: [t('task.list.displayName.profit')],
        color: ['#6da9e8'],
        yAxisData,
        series
      }
    },
    getProfitOption(){
      let data = this.categoryData.profitData.profit || [];
      // data = data.filter(item => item.profitSum > 0)
      if(data.length == 0) return null;

      let yAxisData = [];
      let profitData = [];
      let series = [];

      data.sort((prev, next) => prev.profitSum - next.profitSum).forEach(item => {
        yAxisData.push(item.customerName);

        profitData.push({
          value: item.profitSum,
          _origin: item
        });
      });

      series.push({
        name: t('report.eventScoreChart.label3'),
        type: 'bar',
        barMaxWidth: '20px',
        data: profitData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        legend: [t('report.eventScoreChart.label3')],
        color: ['#6da9e8'],   
        yAxisData,
        series
      }
    },
    getCostOption(){   
      let series = []; 
      let data = this.categoryData.costData.cost || [];
      // data = data.filter(item => item.costSum > 0);
      if(data.length == 0) return null;

      let yAxisData = [];
      let seriesData = [];// 满意       

      data.sort((prev, next) => prev.costSum - next.costSum).forEach(item => {
        yAxisData.push(item.customerName);
        seriesData.push({
          value: item.costSum,
          _origin: item
        });
      });

      series.push({
        name: t('task.list.displayName.cost'),
        type: 'bar',
        barMaxWidth: '20px',
        data: seriesData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        legend: [t('task.list.displayName.cost')],
        color: ['#6da9e8'],
        yAxisData,
        series
      };
    },
    getEventOption(){
      let series = []; 
      let data = this.categoryData.eventData.event || [];
      // data = data.filter(item => item.eventCount > 0);
      if(data.length == 0) return null;

      let yAxisData = [];
      let seriesData = [];// 满意       

      data.sort((prev, next) => prev.eventCount - next.eventCount).forEach(item => {
        yAxisData.push(item.customerName);
        seriesData.push({
          value: item.eventCount,
          _origin: item
        });
      });

      series.push({
        name: t('common.base.event'),
        type: 'bar',
        barMaxWidth: '20px',
        data: seriesData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        legend: [t('common.base.event')],
        color: ['#6da9e8'],
        yAxisData,
        series
      };
    },
    getCategoryOption(option){
      return {
        color: option.color,
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let html = '<div class="chart-tooltip-custom-style">';
            params.forEach((item) => {
              html += `<div>${item.axisValueLabel}</div>`;
              html += `${item.marker} ${item.seriesName}: ${item.value}<br/>`;
            });
            html += '</div>';
            return html;
          }, 
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: option.legend,
          top: '10px',
          left: '70px'
        },
        toolbox: {
          feature: {
            saveAsImage: {
              // TODO国家化翻译待办
              name: `客户${option.legend}统计`
            }
          },
          right: 40
        },
        grid: {
          left: '20px',
          right: '60px',
          bottom: '20px',
          top: '40px',
          containLabel: true
        },
        dataZoom: [
          {
            type: 'slider',
            yAxisIndex: [0]
          }
        ],
        yAxis: {
          type: 'category',
          data: option.yAxisData,
          axisLabel: {
            formatter(value) {
              if (value.length > 5) {
                return `${value.substring(0, 5)}...`
              }
              return value
            },
          },
        },
        xAxis: {
          type: 'value'
        },
        series: option.series
      };
    },
    buildCategoryParams() {
      return {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd,
        tabType: this.currentTabParam
      };
    },
    async fetchCustomerCount(){
      if(this.type !== 'client-satisfaction') return Promise.resolve({});
      let params = {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd,
        type: this.processType,
        // selectType: this.model.selectType,
      }

      if(this.divideByTag) params.tags = this.teamId ? this.teamId.split(',') : [];
      
      const { result, success } = await ReportApi.queryStatsCustomerCount(params);
      return success ? result : {};
    },
    async fetchCategoryData(){
      // 客户满意度统计不请求此接口
      if(this.type === 'client-satisfaction') return Promise.resolve({});
      
      let params = this.buildCategoryParams();
      params.page = 1;

      if(this.divideByTag) params.tagIds = this.teamId ? this.teamId.split(',') : [];

      try {
        const { code, data } = await ReportApi.getAnalysisData(params);
        if(code !== 200) return Promise.resolve({});

        return Promise.resolve(data);
      }catch(e) {
        console.log('fetchCategoryData: ', e)
        return Promise.resolve({});
      }
    },
    async fetchCategoryPagingData(pageNum) {
      let params = this.buildCategoryParams();
      params.page = pageNum || this.tabStatus[this.currentTabParam].pageNum;

      if(this.divideByTag) params.tagIds = this.teamId ? this.teamId.split(',') : [];

      try {
        const { code, data } = await ReportApi.getAnalysisNextpage(params);
        if(code !== 200) return Promise.resolve({});

        return Promise.resolve(data);
      }catch(e) {
        console.log('fetchCategoryPagingData: ', e)
        return Promise.resolve({});
      }
    },

    async fetchCustomerDegree(){
      if(this.type !== 'client-satisfaction') return Promise.resolve({});
      let params = {
        timeStart: this.timeStart,
        timeEnd: this.timeEnd,
        type: this.processType,
      };

      if(this.divideByTag) params.tags = this.teamId ? this.teamId.split(',') : [];

      const { result, success } = await ReportApi.queryStatsCustomerChart(params);
      return success ? result : {};
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      switch (type) {
      case t('common.base.task'):
        this.$tdOnEvent('pc：客户报表-工单数据事件');
        break;
      case t('report.eventScoreChart.label3'):
        this.$tdOnEvent('pc：客户报表-工单营收事件');
        break;
      case t('task.list.displayName.profit'):
        this.$tdOnEvent('pc：客户报表-工单毛利事件');
        break;
      case t('task.list.displayName.cost'):
        this.$tdOnEvent('pc：客户报表-工单成本事件');
        break;
      case t('common.base.event'):
        this.$tdOnEvent('pc：客户报表-服务台事件事件');
        break;
      case 'more':
        this.$tdOnEvent('pc：客户报表-显示更多事件');
        break;
      default:
        break;
      }
    },
    reset() {
      let item = null;
      for(let key in this.tabStatus) {
        item = this.tabStatus[key];

        this.$set(item, 'init', true);
        this.$set(item, 'pageNum', 1);
      }
    },
    datePicker(data) {
      this.type = window.location.href.split('type=')[1]
      this.initDate(data[0], data[1]);
      this.type && this.$track.commonFn.chartTrack(this.type, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    let initData = JSON.parse(sessionStorage.getItem('_init_data'));
    // this.teams = initData.teams || [];
    this.divideByTag = initData.divideByTag || false;
    this.evaluateConfig = initData.evaluateConfig || {};

    this.initChart();
    let that = this
    window.addEventListener('resize', _.debounce(function(){
      if (that.type === 'client-statistics') {
        that.$nextTick(() => {
          chart.resize();
        })
      }
    }, 400))
  },
  watch: {
    category(){
      this.showTable = false;
    },
    expand(){
      this.showTable = false;
      this.setCategoryOption()
    }
  },
  components: {
    [CustomerMap.name]: CustomerMap,
    [CustomerDegreeChart.name]: CustomerDegreeChart,
    [SampleTooltip.name]: SampleTooltip,
    [ClientStatisticsTable.name]: ClientStatisticsTable,
  }
}
</script>

<style lang="scss">
.stats-customer-form{
  padding: 5px 7.5px;
  justify-content: flex-end;
}

.stats-customer-head{
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  margin: 7.5px;
}

.stats-customer-card{
  flex: 1;
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  margin-left: 15px;

  border-radius: 2px;
  background-color: #fff;

  &:first-child{
    margin-left: 0;
  }

  img{
    display: block;
    height: 60px;
    width: 60px;
    border: none;
    margin-right: 10px;
  }
}

.stats-customer-card-info{
  padding: 0 10px;
  flex: 1;
  h3{
    margin: 0;
    padding: 12.5px 0 10px 0;
    font-size: 38px;
    font-weight: 400;
  }

  p{
    color: #666;
    font-size: 18px;
    margin: 0;
    padding: 5px 0 15px 0;
  }
}

.category-chart-wrap{
  width: 100%;
  position: relative;

  .load-more {
    height: 40px;
    line-height: 40px;
    text-align: center;
  }
}

.category-chart-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}

.category-btn-group{
  display: inline-flex;
  flex-flow: row nowrap;
  padding: 10px 0;
  margin: 0 auto;

  button{
    flex: 1;
    outline: none;
    border: 1px solid #ddd;
    border-left: none;
    background-color: #f4f4f4;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
    text-align: center;
    white-space: nowrap;
    transition: all ease .15s;
    border-radius: 0;
  }

  button:hover{
    background-color: #e5e5e5;
  }

  button:first-child{
    border-radius:  2px 0 0 2px ;
    border-left: 1px solid #ddd;
  }

  button:last-child{
    border-radius: 0 2px 2px 0;
  }

  button.stats-checked{
    background-color: $color-primary;
    border-color: $color-primary-light-7;
    color: #fff;
  }
}
</style>

